<?php


namespace App\Web\Model;

use App\Service\EsSearch;
use Elasticsearch\ClientBuilder;

/**
 * 报表数据
 * Class Report
 * @package App\Web\Model
 */
class Report {

    /**
     * 查询团队报表
     * @param $teamCode     起始团队
     * @param $startDate    操作开始时间
     * @param $endDate      操作结束时间
     * @return array
     */
    public function teamReport($teamCode, $startDate, $endDate) {
        //获取团队列表 database
        $teamModel = new Team();
        $teamList = $teamModel->getSubTeamList($teamCode, true);

        //获取团队报表数据 elasticsearch
        $searchFrom = strtotime($startDate);
        $searchTo = strtotime($endDate);
        //获取es查询实例
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::PREFIX => [
                'tagadderteamcode' => $teamCode,
            ],
            EsSearch::RANGE => [
                'updatedate' => [
                    EsSearch::FILE_RANGE_GTE => $searchFrom,
                    EsSearch::FILE_RANGE_LTE => $searchTo,
                ]
            ],
            EsSearch::EQUAL => [
                'status' => '01'
            ]
        ];

        $group = 'group by tagadderteamcode asc top:100, flowat_flowatstatus asc top:150';
        $reportData = $esSearch->setIndex(EsSearch::ES_INDEX_RPO_RELATE_CASE_CASEFLOW)
            ->setFilterPath(EsSearch::FILTER_PATH_AGGS)
            ->setGroupBySql($group)
            ->setWhere($searchWhere)
            ->search();

        $aggData = $esSearch->parseCountAgg($reportData['aggregations']);

        return [
            'teamList' => $teamList,
            'reportData' => $aggData
        ];
    }

    /**
     * 获取团队-项目报表数据
     * @param $teamCode
     * @param $startDate
     * @param $endDate
     * @return array
     */
    public function teamProjectReport($teamCode, $startDate, $endDate) {
        //获取团队报表数据 elasticsearch
        $searchFrom = strtotime($startDate);
        $searchTo = strtotime($endDate);
        //获取es查询实例
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::PREFIX => [
                'tagadderteamcode' => $teamCode,
            ],
            EsSearch::RANGE => [
                'updatedate' => [
                    EsSearch::FILE_RANGE_GTE => $searchFrom,
                    EsSearch::FILE_RANGE_LTE => $searchTo,
                ]
            ],
            EsSearch::EQUAL => [
                'status' => '01'
            ]
        ];

        $group = 'group by projectid asc top:100, flowat_flowatstatus asc top:150';
        $reportData = $esSearch->setIndex(EsSearch::ES_INDEX_RPO_RELATE_CASE_CASEFLOW)
            ->setFilterPath(EsSearch::FILTER_PATH_AGGS)
            ->setGroupBySql($group)
            ->setWhere($searchWhere)
            ->search();

        $aggData = $esSearch->parseCountAgg($reportData['aggregations']);

        $projectIds = [];
        foreach ($aggData as $projectId => $item) {
            $projectIds[] = $projectId;
        }
        $projectModel = new Project();
        $projectList = $projectModel->getProjectListById($projectIds, 'projectid,projectname,crmprojectnum,crmdeliveryway,crmdeliverynum');

        return [
            'projectList' => $projectList,
            'reportData' => $aggData
        ];
    }

    /**
     * 获取团队-项目报表数据
     * @param $teamCode
     * @param $projectId
     * @param $startDate
     * @param $endDate
     * @return void
     */
    public function teamCaseReport($teamCode, $projectId, $startDate, $endDate) {
        //获取团队报表数据 elasticsearch
        $searchFrom = strtotime($startDate);
        $searchTo = strtotime($endDate);
        //获取es查询实例
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::PREFIX => [
                'tagadderteamcode' => $teamCode,
            ],
            EsSearch::RANGE => [
                'updatedate' => [
                    EsSearch::FILE_RANGE_GTE => $searchFrom,
                    EsSearch::FILE_RANGE_LTE => $searchTo,
                ]
            ],
            EsSearch::EQUAL => [
                'status' => '01',
                'projectid' => $projectId
            ]
        ];

        $group = 'group by caseid asc top:100, flowat_flowatstatus asc top:150';
        $reportData = $esSearch->setIndex(EsSearch::ES_INDEX_RPO_RELATE_CASE_CASEFLOW)
            ->setFilterPath(EsSearch::FILTER_PATH_AGGS)
            ->setGroupBySql($group)
            ->setWhere($searchWhere)
            ->search();

        $aggData = $esSearch->parseCountAgg($reportData['aggregations']);

        $caseIds = [];
        foreach ($aggData as $caseId => $item) {
            $caseIds[] = $caseId;
        }
        $caseModel = new CaseModel();
        $caseInfoList = $caseModel->getCaseList($caseIds, 'caseid,casename,vacancy');
        $caseChargeWay = $caseModel->getCaseListChargeWay($caseIds);

        $caseList = [];
        foreach ($caseInfoList as $item) {
            $caseList[$item['caseid']] = [
                'info' => $item,
                'chargeway' => []
            ];
        }
        foreach ($caseChargeWay as $item) {
            if (!isset($caseList[$item['caseid']])) {
                continue;
            }
            $caseList[$item['caseid']]['chargeway'] = $item;
        }

        return [
            'caseList' => $caseList,
            'reportData' => $aggData
        ];
    }

    /**
     * 获取简历明细列表
     * @param $teamCode
     * @param $projectId
     * @param $caseId
     * @param $flowCode
     * @param $startDate
     * @param $endDate
     * @return array
     */
    public function resumeListByTeam($teamCode, $projectId, $caseId, $flowCode, $startDate, $endDate) {
        //获取团队报表数据 elasticsearch
        $searchFrom = strtotime($startDate);
        $searchTo = strtotime($endDate);
        //获取es查询实例
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::PREFIX => [
                'tagadderteamcode' => $teamCode,
            ],
            EsSearch::RANGE => [
                'updatedate' => [
                    EsSearch::FILE_RANGE_GTE => $searchFrom,
                    EsSearch::FILE_RANGE_LTE => $searchTo,
                ]
            ],
            EsSearch::EQUAL => [
                'status' => '01',
            ]
        ];

        if ($projectId > 0) {
            $searchWhere[EsSearch::EQUAL]['projectid'] = $projectId;
        }
        if ($caseId > 0) {
            $searchWhere[EsSearch::EQUAL]['caseid'] = $caseId;
        }
        if (strlen($flowCode) == 2) {
            $searchWhere[EsSearch::EQUAL]['flowat'] = $flowCode;
        } elseif (strlen($flowCode) == 4) {
            $searchWhere[EsSearch::EQUAL]['flowat_flowatstatus'] = $flowCode;
        } else {
            return [
                'totalcount' => 0,
                'keycodelist' => []
            ];
        }

        $data = $esSearch->setIndex(EsSearch::ES_INDEX_RPO_RELATE_CASE_CASEFLOW)
            ->setFields('keycode')
            ->setWhere($searchWhere)
            ->setSize(5000)
            ->setOrder(['updatedate' => EsSearch::ES_DESC])
            ->search();

        $keyCodeList = [];
        foreach ($data['data'] as $item) {
            $keyCodeList[] = $item['keycode'];
        }

        return [
            'totalcount' => $data['totalnum'] ?? 0,
            'keycodelist' => $keyCodeList
        ];
    }

    /**
     * 根据keycode获取简历再职位中的数据
     * @param $oprId
     * @param $keyCodes
     * @return array[]
     */
    public function resumeInfoList($oprId, $keyCodes) {
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::IN => [
                'keycode' => $keyCodes,
            ],
            EsSearch::EQUAL => [
                'status' => '01'
            ]
        ];

        $data = $esSearch->setIndex(EsSearch::ES_INDEX_CASE_EN_RESUME)
            ->setWhere($searchWhere)
            ->search();

        $resumeIds = $caseIds = [];
        $resumeListItem = [];
        foreach ($data['data'] as $item) {
            $resumeIds[] = $item['resumeid'];
            $caseIds[] = $item['caseid'];

            $resumeListItem[$item['keycode']] = $item;
        }

        $resumeList = [];
        foreach ($keyCodes as $keyCode){
            if(isset($resumeListItem[$keyCode])){
                $resumeList[$keyCode] = $resumeListItem[$keyCode];
            }
        }
        unset($resumeListItem);

        //获取简历信息
        $resumeModel = new Manager();
        $resumeInfoList = $resumeModel->getManagerListByResumeId(array_unique($resumeIds), 'cname,userid51job as resumeid');
        $resumeInfoList = $resumeModel->chkDownload($oprId, $resumeInfoList);
        $resumeInfo = [];
        foreach ($resumeInfoList as $item) {
            $resumeInfo[$item['resumeid']] = $item;
        }

        //获取项目信息
        $caseModel = new CaseModel();
        $search['caseids'] = array_unique($caseIds);
        if (empty($search['caseids'])) {
            $caseInfoList = [];
        } else {
            $caseInfoList = $caseModel->search($search, 'c.casename,c.caseid,c.projectid,c.subid,Project.projectname', 0, 0, true);
        }

        $caseInfo = [];
        foreach ($caseInfoList as $item) {
            $caseInfo[$item['caseid']] = $item;
        }
        return [
            'resumeList' => $resumeList,
            'resumeInfo' => $resumeInfo,
            'caseInfo' => $caseInfo
        ];
    }

    /**
     * 查询用户报表
     * @param array $userIds
     * @param $startDate
     * @param $endDate
     */
    public function userReport(array $userIds, $startDate, $endDate) {
        if (empty($userIds)) {
            return [
                'reportData' => []
            ];
        }
        //根据团队id查询用户数据
        //获取团队报表数据 elasticsearch
        $searchFrom = strtotime($startDate);
        $searchTo = strtotime($endDate);
        //获取es查询实例
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::IN => [
                'creator' => $userIds,
            ],
            EsSearch::RANGE => [
                'updatedate' => [
                    EsSearch::FILE_RANGE_GTE => $searchFrom,
                    EsSearch::FILE_RANGE_LTE => $searchTo,
                ]
            ],
            EsSearch::EQUAL => [
                'status' => '01'
            ]
        ];

        $group = 'group by creator asc top:500, flowat_flowatstatus asc top:150';
        $reportData = $esSearch->setIndex(EsSearch::ES_INDEX_RPO_RELATE_CASE_CASEFLOW)
            ->setFilterPath(EsSearch::FILTER_PATH_AGGS)
            ->setGroupBySql($group)
            ->setWhere($searchWhere)
            ->search();

        $aggData = $esSearch->parseCountAgg($reportData['aggregations']);

        return [
            'reportData' => $aggData
        ];
    }

    /**
     * 获取用户-项目报表数据
     * @param $userId
     * @param $startDate
     * @param $endDate
     * @return array
     */
    public function userProjectReport($userId, $startDate, $endDate) {
        //获取团队报表数据 elasticsearch
        $searchFrom = strtotime($startDate);
        $searchTo = strtotime($endDate);
        //获取es查询实例
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::RANGE => [
                'updatedate' => [
                    EsSearch::FILE_RANGE_GTE => $searchFrom,
                    EsSearch::FILE_RANGE_LTE => $searchTo,
                ]
            ],
            EsSearch::EQUAL => [
                'creator' => $userId,
                'status' => '01'
            ]
        ];

        $group = 'group by projectid asc top:100, flowat_flowatstatus asc top:150';
        $reportData = $esSearch->setIndex(EsSearch::ES_INDEX_RPO_RELATE_CASE_CASEFLOW)
            ->setFilterPath(EsSearch::FILTER_PATH_AGGS)
            ->setGroupBySql($group)
            ->setWhere($searchWhere)
            ->search();

        $aggData = $esSearch->parseCountAgg($reportData['aggregations']);

        $projectIds = [];
        foreach ($aggData as $projectId => $item) {
            $projectIds[] = $projectId;
        }
        $projectModel = new Project();
        $projectList = $projectModel->getProjectListById($projectIds, 'projectid,projectname,crmprojectnum,crmdeliveryway,crmdeliverynum');

        return [
            'projectList' => $projectList,
            'reportData' => $aggData
        ];
    }

    /**
     * 获取团队-项目报表数据
     * @param $userId
     * @param $projectId
     * @param $startDate
     * @param $endDate
     * @return array
     */
    public function userCaseReport($userId, $projectId, $startDate, $endDate) {
        //获取团队报表数据 elasticsearch
        $searchFrom = strtotime($startDate);
        $searchTo = strtotime($endDate);
        //获取es查询实例
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::RANGE => [
                'updatedate' => [
                    EsSearch::FILE_RANGE_GTE => $searchFrom,
                    EsSearch::FILE_RANGE_LTE => $searchTo,
                ]
            ],
            EsSearch::EQUAL => [
                'creator' => $userId,
                'projectid' => $projectId,
                'status' => '01',
            ]
        ];

        $group = 'group by caseid asc top:100, flowat_flowatstatus asc top:150';
        $reportData = $esSearch->setIndex(EsSearch::ES_INDEX_RPO_RELATE_CASE_CASEFLOW)
            ->setFilterPath(EsSearch::FILTER_PATH_AGGS)
            ->setGroupBySql($group)
            ->setWhere($searchWhere)
            ->search();

        $aggData = $esSearch->parseCountAgg($reportData['aggregations']);

        $caseIds = [];
        foreach ($aggData as $caseId => $item) {
            $caseIds[] = $caseId;
        }
        $caseModel = new CaseModel();
        $caseInfoList = $caseModel->getCaseList($caseIds, 'caseid,casename,vacancy');
        $caseChargeWay = $caseModel->getCaseListChargeWay($caseIds);

        $caseList = [];
        foreach ($caseInfoList as $item) {
            $caseList[$item['caseid']] = [
                'info' => $item,
                'chargeway' => []
            ];
        }
        foreach ($caseChargeWay as $item) {
            if (!isset($caseList[$item['caseid']])) {
                continue;
            }
            $caseList[$item['caseid']]['chargeway'] = $item;
        }

        return [
            'caseList' => $caseList,
            'reportData' => $aggData
        ];
    }

    /**
     * 获取简历明细列表
     * @param $userId
     * @param $projectId
     * @param $caseId
     * @param $flowCode
     * @param $startDate
     * @param $endDate
     * @return array
     */
    public function resumeListByUser($userId, $projectId, $caseId, $flowCode, $startDate, $endDate) {
        //获取团队报表数据 elasticsearch
        $searchFrom = strtotime($startDate);
        $searchTo = strtotime($endDate);
        //获取es查询实例
        $esSearch = EsSearch::getInstance();
        $searchWhere = [
            EsSearch::RANGE => [
                'updatedate' => [
                    EsSearch::FILE_RANGE_GTE => $searchFrom,
                    EsSearch::FILE_RANGE_LTE => $searchTo,
                ]
            ],
            EsSearch::EQUAL => [
                'creator' => $userId,
                'status' => '01',
            ]
        ];

        if ($projectId > 0) {
            $searchWhere[EsSearch::EQUAL]['projectid'] = $projectId;
        }
        if ($caseId > 0) {
            $searchWhere[EsSearch::EQUAL]['caseid'] = $caseId;
        }
        if (strlen($flowCode) == 2) {
            $searchWhere[EsSearch::EQUAL]['flowat'] = $flowCode;
        } elseif (strlen($flowCode) == 4) {
            $searchWhere[EsSearch::EQUAL]['flowat_flowatstatus'] = $flowCode;
        } else {
            return [
                'totalcount' => 0,
                'keycodelist' => []
            ];
        }

        $data = $esSearch->setIndex(EsSearch::ES_INDEX_RPO_RELATE_CASE_CASEFLOW)
            ->setFields('keycode')
            ->setWhere($searchWhere)
            ->setSize(5000)
            ->setOrder(['updatedate' => EsSearch::ES_DESC])
            ->search();

        $keyCodeList = [];
        foreach ($data['data'] as $item) {
            $keyCodeList[] = $item['keycode'];
        }

        return [
            'totalcount' => $data['totalnum'] ?? 0,
            'keycodelist' => $keyCodeList
        ];
    }
}